import Vue from 'vue'
import Vuex from 'vuex'
import { loginIn } from '@/api'
import { getToken, setToken, removeToken, setRoutes, getRoutes } from '@/utils/auth'
import { Notification } from 'element-ui';
Vue.use(Vuex)

const state = {
    token: getToken(),
    msg: '我是主应用的数据', //发送给子应用的和数据
    isCollapse: false,//layout 侧边导航折叠
    childArr: [],//当前加载的多个子应用数组
    breadRoutes: getRoutes(),//面包蟹导航
    sendData: ''//接收来自子应用的数据
}
const getters = {
    token(state) {
        return state.token
    }
}

const mutations = {
    //折叠状态
    CHANGE_COLLAPSE(state) {
        state.isCollapse = !state.isCollapse
    },
    CHILD_ARR(state, data) {
        state.childArr = data
    },
    BREAD_ROUTES(state, data) {
        state.breadRoutes = data
    },
    SET_TOKEN(state, data) {
        state.token = data
    },
    SEND_DATA(state, data) {
        Notification.success({
          title: '主应用',
          message: `接收数据：${data}`,
          type: 'success'
        })
        state.sendData = data
    }
}
const actions = {
    childArr({ commit }, data) {
        commit('CHILD_ARR', data)
    },
    breadRoutes({ commit }, data) {
        return new Promise(resolve => {
            setTimeout(() => {
                setRoutes(JSON.stringify(data))
                commit('BREAD_ROUTES', data)
                resolve()
            })
        })
    },
    userLogin({ commit }, data) {
        return new Promise(resolve => {
            loginIn(data).then((res) => {
                setToken(res.token)
                commit('SET_TOKEN', res.token)
                resolve()
            }).catch(() => { })
        })
    },
    loginOut({ commit }) {
        return new Promise(resolve => {
            setTimeout(() => {
                removeToken()
                commit('SET_TOKEN', '')
                resolve()
            })
        })
    },
    sendData({ commit }, data) {
        commit('SEND_DATA', data)
    }
}

export default new Vuex.Store({
    state,
    getters,
    mutations,
    actions
})